package cn.mania_man.trpg_helper_server.room;

import cn.mania_man.trpg_helper_server.util.ResponseUtil;
import cn.mania_man.trpg_helper_server.websocket.MessageSender;
import cn.mania_man.trpg_helper_server.websocket.User;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

public class Room {
    private static final Set<Room> roomMap = new HashSet<>();
    private final Set<User> users = new HashSet<>();
    private String password;
    private String enterPassword;

    private String name;

    public static Set<Room> getRoomSet() {
        return roomMap;
    }


    /**
     * 加入某个user到房间
     */
    public void join(User user) {
        getUsers().add(user);
        MessageSender.PushMessage(ResponseUtil.userList(this));
        MessageSender.PushMessage(ResponseUtil.massage("用户：" + user.getUserName() + "已进入房间", "*", user.getRoom()));
    }

    /**
     * 从房间移除某个user
     */
    public void exit(User user) {
        this.users.remove(user);
        if (this.users.size() == 0) {
            roomMap.remove(this);
            this.close();
        }
        MessageSender.PushMessage(ResponseUtil.userList(this));
        MessageSender.PushMessage(ResponseUtil.massage("用户：" + user.getUserName() + "已退出", "*", user.getRoom()));
    }

    /**
     * 关闭房间，注意：不会将房间从房间列表移除
     */
    public void close() {

        new HashSet<>(this.users).forEach(user -> user.close(1000, "房间已关闭"));
    }


    public Set<User> getUsers() {
        return users;
    }


    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEnterPassword() {
        return enterPassword;
    }

    public void setEnterPassword(String enterPassword) {
        this.enterPassword = enterPassword;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
